package main

import (
	"embed"
	_ "embed"
	"log"
	"time"

	_ "gitee.com/chunanyong/dm" // Import DaMeng database driver
	"github.com/wailsapp/wails/v3/pkg/application"

	"changeme/internal/services"
)

// Wails uses Go's `embed` package to embed the frontend files into the binary.
// Any files in the frontend/dist folder will be embedded into the binary and
// made available to the frontend.
// See https://pkg.go.dev/embed for more information.

//go:embed all:frontend/dist
var assets embed.FS

// main function serves as the application's entry point. It initializes the application, creates a window,
// and starts a goroutine that emits a time-based event every second. It subsequently runs the application and
// logs any error that might occur.
func main() {

	// 创建数据库服务
	dbService, err := services.NewDatabaseService()
	if err != nil {
		log.Fatal("Failed to create database service:", err)
	}

	// 创建窗口服务
	windowService := services.NewWindowService()

	// Create a new Wails application by providing the necessary options.
	// Variables 'Name' and 'Description' are for application metadata.
	// 'Assets' configures the asset server with the 'FS' variable pointing to the frontend files.
	// 'Services' is a list of Go struct instances. The frontend has access to the methods of these instances.
	// 'Mac' options tailor the application when running an macOS.
	app := application.New(application.Options{
		Name:        "Database Manager",
		Description: "A professional database management tool built with Wails3 and Vue3",
		Services: []application.Service{
			application.NewService(dbService),
			application.NewService(windowService),
		},
		Assets: application.AssetOptions{
			Handler: application.AssetFileServerFS(assets),
		},
		Mac: application.MacOptions{
			ApplicationShouldTerminateAfterLastWindowClosed: true,
		},
	})

	// 设置窗口服务的应用实例
	windowService.SetApp(app)

	// Create a new window with the necessary options.
	// 'Title' is the title of the window.
	// 'Mac' options tailor the window when running on macOS.
	// 'BackgroundColour' is the background colour of the window.
	// 'URL' is the URL that will be loaded into the webview.
	mainWindow := app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{
		Title: "Database Manager",
		Name:  "main",
		Mac: application.MacWindow{
			InvisibleTitleBarHeight: 50,
			Backdrop:                application.MacBackdropTranslucent,
			TitleBar:                application.MacTitleBarHiddenInset,
		},
		BackgroundColour: application.NewRGB(27, 38, 54),
		URL:              "/",
		Width:            1200,
		Height:           800,
		MinWidth:         800,
		MinHeight:        600,
	})

	// 监听导入成功事件，在主窗口中刷新数据
	app.OnEvent("import:success", func(e *application.CustomEvent) {
		// 可以在这里通知主窗口刷新表数据
		mainWindow.EmitEvent("refresh:table-data", e.Data)
	})

	// Create a goroutine that emits an event containing the current time every second.
	// The frontend can listen to this event and update the UI accordingly.
	go func() {
		for {
			now := time.Now().Format(time.RFC1123)
			app.EmitEvent("time", now)
			time.Sleep(time.Second)
		}
	}()

	// 应用关闭时清理资源
	defer func() {
		if err := dbService.Shutdown(); err != nil {
			log.Printf("Error shutting down database service: %v", err)
		}
	}()

	// Run the application. This blocks until the application has been exited.
	err = app.Run()

	// If an error occurred while running the application, log it and exit.
	if err != nil {
		log.Fatal(err)
	}
}
